from flask import Blueprint
from flask import request
import re
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_jwt_extended import create_access_token, create_refresh_token
from app.services.user_service import get_user_by_username, create_user, get_user_info_by_id, update_user_info_by_id, \
    update_user_password_by_id
from app.utils.md5 import md5_hash
from app.utils.response import success, error

user_bp = Blueprint('user', __name__, url_prefix='/user')

"""
用户登录
"""
@user_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    if not username or not password:
        return error(msg='用户名和密码不能为空')
    
    user = get_user_by_username(username)

    if not user or user.password != md5_hash(password):
        return error(msg='用户名或密码错误')
    try:
        # 生成访问令牌和刷新令牌
        access_token = create_access_token(identity=user.id)
        refresh_token = create_refresh_token(identity=user.id)
    except Exception as e:
        return error(msg='生成令牌失败')
    return success(f'Bearer {access_token}')

"""
用户注册
"""
@user_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()

    # 校验数据
    username = data.get('username')
    password = data.get('password')
    nickname = data.get('nickname')
    confirmPassword = data.get('confirmPassword')
    phone = data.get('phone')
    email = data.get('email')

    user = get_user_by_username(username)
    if user:
        return error(msg='用户名已存在')

    if not username or not password:
        return error(msg='用户名和密码不能为空')

    if not re.match(r'^[a-zA-Z0-9_-]{3,16}$', username):
        return error(msg='用户名只能包含字母、数字、下划线、减号，长度为3到16个字符')

    if not re.match('^[\u4e00-\u9fa5a-zA-Z0-9_]{2,10}$', nickname):
        return error(msg='昵称只能包含中文、字母、数字、下划线，长度为2到10个字符')

    if not re.match('^1[3-9]\d{9}$', phone):
        return error(msg='手机号格式不正确')

    if not re.match('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', email):
        return error(msg='邮箱格式不正确')

    if password != confirmPassword:
        return error(msg='两次密码不一致')

    # 密码加密
    hashed_password = md5_hash(password)
    user = create_user(username, hashed_password, nickname=nickname, phone=phone, email=email)
    return success() if user else error(msg='注册失败')


"""
获取用户信息
"""
@user_bp.route('/info', methods=['GET'])
@jwt_required()
def get_user_info():
    user_id = get_jwt_identity()
    user_info = get_user_info_by_id(user_id)
    if user_info:
        return success(user_info)
    else:
        return error(msg='获取用户信息失败')

"""
用户修改信息
"""
@user_bp.route('/info', methods=['PUT'])
@jwt_required()
def update_user_info():
    data = request.get_json()
    user_id = get_jwt_identity()
    user = update_user_info_by_id(user_id, data)
    if user:
        return success(user)
    else:
        return error(msg='修改用户信息失败')

"""
用户修改密码
"""
@user_bp.route('/changePwd', methods=['PUT'])
@jwt_required()
def update_user_password():
    data = request.get_json()
    user_id = get_jwt_identity()
    old_password = data.get('oldPassword')
    new_password = data.get('newPassword')
    confirm_password = data.get('confirmPassword')
    # 校验数据
    if not old_password or not new_password or not confirm_password:
        return error(msg='旧密码、新密码和确认密码不能为空')

    if new_password != confirm_password:
        return error(msg='两次密码不一致')

    new_password = md5_hash(new_password)
    if update_user_password_by_id(user_id, new_password):
        return success()
    else:
        return error(msg='修改密码失败')